﻿using AutoMapper;
using MediatR;
using ProductManagement.Applcation.Command;
using ProductManagement.Domain.ProductsDomain;
using ProductManagement.Infrstructre.Interface;

namespace ProductManagement.Applcation.CommandHanlers
{
    /// <summary>
    /// 产品分类新增
    /// </summary>
    public class ProductTypeCreateCommandHandlers : IRequestHandler<ProductTypeCreateCommand, int>
    {
        protected readonly InterfaceProductsTypeRepository repository;
        protected readonly IMapper mapper;

        public ProductTypeCreateCommandHandlers(InterfaceProductsTypeRepository repository, IMapper mapper)
        {
            this.repository = repository;
            this.mapper = mapper;
        }

        public async Task<int> Handle(ProductTypeCreateCommand request, CancellationToken cancellationToken)
        {
            var newAdds = (await repository.GetAll()).Where(x => x.PTClass == request.AddDtos.PTClass).ToList();
            //判断是否存在相同分类
            if (newAdds.Count > 0)
            {
                return -1;
            }
            else
            {
                return await repository.AddAsync(mapper.Map<ProductType>(request.AddDtos));
            }

        }

    }
}
